package ca.ualberta.cs.CLRServer.Interface;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.WebApplicationException;

import ca.ualberta.cs.CLRServer.resources.JAXBBean;

public class SecureResource {

	/**
	 * Checks the format and size of the url given in the request being processed
	 * @param url
	 */
	protected void checkUrl(String url){
		if(url.length() > 1000)
			throw new WebApplicationException(414);
		try{
			new URI(url);
		} catch (URISyntaxException e) {
			throw new WebApplicationException(415);
		}
	}
	
	/**
	 * Checks that the coming request (List<JAXBBean>) doesn't have an unusual size (buffer flow - attack)
	 * The unusual size is considered greater than the given maxLimit. If maxLimit is not known, another method with default value of 15 is called {@link "protected void checkBufferOverflow(List<JAXBBean> requestArr)"}
	 * @param requestArr
	 * @param maxLimit
	 */
	protected void checkBufferOverflow(List<JAXBBean> requestArr, int maxLimit){
		if(requestArr.size() > maxLimit)
			throw new WebApplicationException(413);
	}
	
	/**
	 * Checks that the coming request (List<JAXBBean>) doesn't have an unusual size (buffer flow - attack)
	 * The normal size according to the designated client (CoRAL fab4browser) should not be more than 15
	 * @param requestArr
	 */
	protected void checkBufferOverflow(List<JAXBBean> requestArr){
		if(requestArr.size() > 15)
			throw new WebApplicationException(413);
	}
	
	/**
	 * Makes sure that all required fields are contained in the request : makes sure that the request is what is expected
	 * @param requestArr
	 * @param keys : the required keys to handle a request
	 */
	protected void checkRequiredKeys(List<JAXBBean> requestArr, String... keys){
		for(String key : keys){
			boolean exists = false;
			for(JAXBBean bean : requestArr){
				if(bean.getKey().equals(key)){
					exists = true;
					break; //look for next key
				}
			}
			if( !exists ) //if one key does not exist
				throw new WebApplicationException(415);
		}
	}
}
